/*
 *  Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package io.seata.sample.conf;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.AnsiSqlDialect;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.druid.DruidPlugin;
import io.seata.sample.plugin.SeataDruidPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.util.UUID;

/**
 * The type Druid configuration.
 */
@Configuration
public class JFinalConfiguration {

	@Value("${spring.datasource.url}")
	private String url;

	@Value("${spring.datasource.username}")
	private String username;

	@Value("${spring.datasource.password}")
	private String password;

	@Autowired
	public void initDataSource() {
		System.out.println("初始化数据源....");
		// 使用Seata Plugin初始化
		DruidPlugin plugin = new SeataDruidPlugin(url, username, password);
		plugin.start();
		System.out.println("数据源初始化完成！");

		System.out.println("初始化Active Record...");
		ActiveRecordPlugin arp = initArp(plugin,url);
		arp.start();
		System.out.println("Active Record初始化完成！");
	}

	public static ActiveRecordPlugin initArp(DruidPlugin druid, String dbUrl) {
		ActiveRecordPlugin arp = new ActiveRecordPlugin(UUID.randomUUID().toString(),druid, Connection.TRANSACTION_SERIALIZABLE);
		arp.setDialect(new AnsiSqlDialect());
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
		if (dbUrl.contains("sqlite")) {
			// 对sqlite设定专门的事务层级
//            arp.setTransactionLevel(Connection.TRANSACTION_READ_UNCOMMITTED);
			arp.setTransactionLevel(Connection.TRANSACTION_SERIALIZABLE);
			arp.setDialect(new Sqlite3Dialect());
		}
		else if (dbUrl.contains("mysql")) {
			arp.setDialect(new MysqlDialect());
		}
		return arp;
	}
}
